'*************************************************
' Spawn process and wait for its child, with hint
'*************************************************

If WScript.Arguments.Count <> 2 Then
	WScript.Echo "Usage: waitpwhint.vbs <path to exec> <wait hint>"
	WScript.Quit 1
End If

Dim objShell : Set objShell = WScript.CreateObject("WScript.Shell")

targetPID = 0

strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
	& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colRecent = objWMIService.ExecNotificationQuery("SELECT * FROM __InstanceCreationEvent " _
	& "within 1 WHERE TargetInstance isa 'Win32_Process'")

Dim objSpawn : Set objSpawn = objShell.Exec(WScript.Arguments(0))
parentPID = objSpawn.ProcessId

Do While True
	Set objLatest = colRecent.NextEvent
	If InStr(objLatest.TargetInstance.Name, WScript.Arguments(1)) > 0 And _
		objLatest.TargetInstance.ParentProcessId = parentPID Then
		targetPID = objLatest.TargetInstance.ProcessId
		Exit Do
	End If 
Loop

If targetPID > 0 Then
	Set colRecent = objWMIService.ExecNotificationQuery("SELECT * FROM __InstanceDeletionEvent " _
		& "within 1 WHERE TargetInstance isa 'Win32_Process'")
	Do While True
		Set objLatest = colRecent.NextEvent
		If objLatest.TargetInstance.ProcessId = targetPID Then
			Exit Do
		End If
	Loop
End If
